import React, { useState, useEffect } from "react";
import { Button, Input, message, Space, Radio, Tooltip } from "antd";
import {
  CopyOutlined,
  CompressOutlined,
  DeleteOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
import { copyToClipboard } from "@/utils/clipboard";
import ReactJson from "react-json-view";
import ToolTitle from "@/components/ToolTitle";
import { textToolsData } from "@/components/ToolsData";

const { TextArea } = Input;

const jsonViewTheme = {
  base00: "transparent",
  base01: "#ddd",
  base02: "#e0e0e0",
  base03: "#9e9e9e",
  base04: "#8a8a8a",
  base05: "#616161",
  base06: "#424242",
  base07: "#212121",
  base08: "#c41a16",
  base09: "#ffa000",
  base0A: "#ffc107",
  base0B: "#4caf50",
  base0C: "#00bcd4",
  base0D: "#2196f3",
  base0E: "#9c27b0",
  base0F: "#f44336",
};

const JsonFormat: React.FC = () => {
  const [inputText, setInputText] = useState<string>("");
  const [outputText, setOutputText] = useState<string>("");
  const [indentSize, setIndentSize] = useState<number>(4);
  const [isValid, setIsValid] = useState<boolean>(true);

  useEffect(() => {
    if (inputText.trim() === "") {
      setOutputText("");
      setIsValid(true);
      return;
    }

    try {
      const parsedJson = JSON.parse(inputText);
      const formatted = JSON.stringify(parsedJson, null, indentSize);
      setOutputText(formatted);
      setIsValid(true);
    } catch (error) {
      setIsValid(false);
      setOutputText(`错误: ${(error as Error).message}`);
    }
  }, [inputText, indentSize]);

  const handleFormat = () => {
    if (inputText.trim() === "") {
      message.warning("请输入JSON内容");
      return;
    }

    try {
      const parsedJson = JSON.parse(inputText);
      const formatted = JSON.stringify(parsedJson, null, indentSize);
      setOutputText(formatted);
      setIsValid(true);
      message.success("格式化成功");
    } catch (error) {
      setIsValid(false);
      setOutputText(`错误: ${(error as Error).message}`);
      message.error("JSON格式无效，请检查");
    }
  };

  const handleCompress = () => {
    if (!isValid || inputText.trim() === "") {
      message.warning("请先输入有效的JSON");
      return;
    }

    try {
      const parsedJson = JSON.parse(inputText);
      const compressed = JSON.stringify(parsedJson);
      setOutputText(compressed);
      message.success("压缩成功");
    } catch (error) {
      console.error("JSON压缩失败:", error);
      message.error("压缩失败");
    }
  };

  const handleCopy = () => {
    if (isValid && inputText) {
      copyToClipboard(JSON.stringify(JSON.parse(inputText), null, indentSize));
      message.success("已复制到剪贴板");
    } else if (outputText) {
      copyToClipboard(outputText);
      message.success("已复制到剪贴板");
    } else {
      message.warning("没有内容可复制");
    }
  };

  const handleClear = () => {
    setInputText("");
    setOutputText("");
    message.info("已清空");
  };

  const handleDownload = () => {
    if (!outputText && !inputText) {
      message.warning("没有内容可下载");
      return;
    }

    try {
      const content = isValid
        ? JSON.stringify(JSON.parse(inputText), null, indentSize)
        : outputText;
      const blob = new Blob([content], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `formatted-${new Date().getTime()}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      message.success("下载成功");
    } catch (error) {
      console.error("下载失败:", error);
      message.error("下载失败");
    }
  };

  return (
    <div className="p-6">
      <ToolTitle
        title={
          textToolsData.find((item) => item.title === "JSON格式化")?.title || ""
        }
        description={
          textToolsData.find((item) => item.title === "JSON格式化")
            ?.description || ""
        }
      />

      <div className="grid md:grid-cols-2 gap-6 h-[calc(100vh-180px)]">
        <div className="flex flex-col h-full">
          <div className="flex justify-between items-center mb-4">
            <span className="font-medium text-base">输入JSON:</span>
            <Radio.Group
              value={indentSize}
              onChange={(e) => setIndentSize(e.target.value)}
              buttonStyle="solid"
              size="middle"
              className="rounded-lg p-1"
            >
              <Space size="middle">
                <Tooltip title="2空格缩进">
                  <Radio.Button value={2} className="px-4 py-2 text-base">
                    2空格
                  </Radio.Button>
                </Tooltip>
                <Tooltip title="4空格缩进">
                  <Radio.Button value={4} className="px-4 py-2 text-base">
                    4空格
                  </Radio.Button>
                </Tooltip>
              </Space>
            </Radio.Group>
          </div>
          <TextArea
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            placeholder="请在此输入JSON内容..."
            className={`w-full flex-1 ${
              !isValid && inputText ? "border-red-500" : ""
            }`}
            style={{
              fontFamily: "monospace",
              height: "100%",
              resize: "none",
            }}
          />
        </div>

        <div className="flex flex-col h-full">
          <div className="flex justify-between items-center mb-4">
            <span className="font-medium text-base">格式化结果:</span>
            <Space>
              <Button type="primary" onClick={handleFormat}>
                格式化
              </Button>
              <Button icon={<CompressOutlined />} onClick={handleCompress}>
                压缩
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={handleDownload}
                disabled={!outputText && !inputText}
              >
                下载
              </Button>
              <Button
                icon={<CopyOutlined />}
                onClick={handleCopy}
                disabled={!outputText}
              >
                复制
              </Button>
              <Button icon={<DeleteOutlined />} onClick={handleClear}>
                清空
              </Button>
            </Space>
          </div>

          {isValid && inputText ? (
            <div className="w-full h-full flex-1 p-4 bg-white rounded border">
              <ReactJson
                src={JSON.parse(inputText)}
                theme={jsonViewTheme}
                name={false}
                indentWidth={indentSize}
                collapsed={2}
                collapseStringsAfterLength={50}
                displayDataTypes={false}
                style={{
                  fontFamily: "monospace",
                  height: "100%",
                  overflow: "auto",
                }}
              />
            </div>
          ) : (
            <TextArea
              value={outputText}
              readOnly
              rows={20}
              className="w-full h-full flex-1"
              style={{
                fontFamily: "monospace",
                height: "100%",
                resize: "none",
              }}
            />
          )}
        </div>
      </div>

      <div className="mt-6 text-gray-500 text-sm">
        <p>使用提示:</p>
        <ul className="list-disc pl-5">
          <li>输入JSON数据后点击"格式化"按钮进行美化</li>
          <li>使用"压缩"按钮可将JSON压缩为一行</li>
          <li>可选择2空格或4空格缩进</li>
          <li>格式化结果可直接复制到剪贴板</li>
        </ul>
      </div>
    </div>
  );
};

export default JsonFormat;
